package gosnoopers.fr;

import java.util.ArrayList;
import java.util.HashMap;

import lazy_listview.JSONfunctions;
import listview.CountriesAdapterDialog;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

import common.Common;

public class MainActivity extends Activity {
	private Button  btn_sign_up;

	
	public static EditText _username,_pass;

	public static String username = null;
	public static String pass = null;
	private int inscription_focus = 0;
	

	final Context context = this;
	ArrayList<HashMap<String, String>> arraylistCountries;
	public static JSONObject jsonobjectCountries;
	public static JSONArray jsonarrayCountries;
	ListView listCountries;
	CountriesAdapterDialog adapterCountries;
	public static String[] valuesageCountry = new String[] { "AAAA" };

	ArrayList<HashMap<String, String>> arraylistCities;
	public static JSONObject jsonobjectCities;
	public static JSONArray jsonarrayCities;
	ListView listCities;
	CountriesAdapterDialog adapterCities;
	public static String[] valuesageCities = new String[] { "BBB" };


	

	



	/**
	 * Reset Form
	 */
	@Override
	protected void onResume() {
		super.onResume();
		
		
		
	}


	public boolean isNetworkAvailable() {
		ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetworkInfo = connectivityManager
				.getActiveNetworkInfo();
		return activeNetworkInfo != null && activeNetworkInfo.isConnected();
	}

	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		setContentView(R.layout.login);
		/*if(MainActivity.userId.equalsIgnoreCase("0")){
			
		}*/
		inscription_focus = getIntent().getIntExtra("inscription", 0);
		
		_username = (EditText) findViewById(R.id.username);
		_pass = (EditText) findViewById(R.id.pass);
		username = _username.getText().toString();
		pass = _pass.getText().toString();
		btn_sign_up = (Button) findViewById(R.id.signin);
		btn_sign_up.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				
				AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
						context);
				alertDialogBuilder.setTitle("GOSNOOPERS");
				
				
				if( _username.getText().toString().matches("")) {
					alertDialogBuilder
							.setMessage("Please type username!")
							.setCancelable(false)
							.setNegativeButton("OK",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											dialog.cancel();
										}
									});
					AlertDialog alertDialog = alertDialogBuilder.create();
					alertDialog.show();
				} else if ( _pass.getText().toString().matches("")) {
					alertDialogBuilder
							.setMessage("Please choose password!")
							.setCancelable(false)
							.setNegativeButton("OK",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											dialog.cancel();
										}
									});
					AlertDialog alertDialog = alertDialogBuilder.create();
					alertDialog.show();
				} else {
					


					if (!isNetworkAvailable()) {

						Toast toast = Toast.makeText(getApplicationContext(),
								Common.MSG, Toast.LENGTH_SHORT);
						toast.show();
					} else {
						new Save().execute();
					}

				}

			}
		});
		
	}


	ProgressDialog mProgressDialog;
	ArrayList<HashMap<String, String>> arraylist;
	static String ID = "id";
	static String NAME = "name";
	static String ALIAS = "alias";
	public static JSONObject jsonobject;
	public static JSONArray jsonarray;
	public static String userId = "0";
	ListView list;
	boolean checkError = false;
	String message = "";
	
	
	
	
	// DownloadJSON AsyncTask
	private class Save extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			btn_sign_up.setEnabled(false);
			ProgressBar progressbar_sign_up = (ProgressBar) findViewById(R.id.progressbar_sign_up);
			progressbar_sign_up.setVisibility(View.VISIBLE);
		}

		@Override
		protected Void doInBackground(Void... params) {
			// Create an array
			arraylist = new ArrayList<HashMap<String, String>>();
			// Retrieve JSON Objects from the given URL address

			String paramsURL = "username="
					+ _username.getText().toString()
					+ "&password="
					+ _pass.getText().toString();
			
			jsonobject = JSONfunctions.executeUrlWithOption(true,"http://gosnoopers.com/user/app/login", paramsURL, false);
			Log.d("FORM FIRST", "Json get post !!!!!!!!!!!: " + jsonobject);
			Log.i("username", _username.getText().toString());
			Log.i("pass", _pass.getText().toString());
			Log.i("paramsURL", paramsURL);
			try {
				checkError = jsonobject.getBoolean("error");
				message = jsonobject.getString("message");
				userId = jsonobject.getString("userId");
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			Log.i("AAAAAAAAAAAAAAAAAA",userId);
			ProgressBar progressbar_sign_up = (ProgressBar) findViewById(R.id.progressbar_sign_up);
			progressbar_sign_up.setVisibility(View.GONE);
			if(!checkError && jsonobject.length()!=0){
				if(inscription_focus==1) {
					Intent insAct = new Intent(getApplicationContext(), InscriptionActivity.class);
	                startActivity(insAct);
				}else{
					Intent goToNextActivity = new Intent(getApplicationContext(), HomePage.class);
	                startActivity(goToNextActivity);
				}
				
			}else{
				
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
						context);
				alertDialogBuilder.setTitle("GOSNOOPERS");
				alertDialogBuilder
				.setMessage(message)
				.setCancelable(false)
				.setNegativeButton("OK",
						new DialogInterface.OnClickListener() {
							public void onClick(
									DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});
				AlertDialog alertDialog = alertDialogBuilder.create();
				alertDialog.show();
			}
			btn_sign_up.setEnabled(true);
			
		}
	}

}